<?php
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

	function getMgmConfig() {
		global $database;
		$config = Array();
        if (defined( '_JEXEC' )) {
            $table = "plugins";
        } elseif (defined( '_VALID_MOS' )) {
            $table = "mambots";
        }
		$query = "SELECT id FROM #__$table WHERE element = 'mgmediabot2' AND folder = 'content'";
		$database->setQuery( $query );
		$id = $database->loadResult();
		$mambot = new mosMambot( $database );
		$mambot->load( $id );
		$mambotParams =& new mosParameters( $mambot->params );
		$config['popupAutorun'] = $mambotParams->get( 'popupAutorun', '1' );
		$config['contentAutorun'] = $mambotParams->get( 'contentAutorun', '0' );
		$config['debug'] = $mambotParams->get( 'debug', '0' );
        # get current template path
		$query = "SELECT template FROM #__templates_menu WHERE client_id='0' AND menuid='0'";
        $database->setQuery( $query );
        $config['j_template'] = $database->loadResult();
        // Assigned template
        if ( isset( $Itemid ) && $Itemid != "" && $Itemid != 0 ) {
            $query = "SELECT template FROM #__templates_menu WHERE client_id='0' AND menuid='$Itemid' LIMIT 1";
            $database->setQuery( $query );
            $config['j_template'] = $database->loadResult() ? $database->loadResult() : $config['j_template'];
        }
		return $config;
	}

	function outputMgmPlayer2($type, $path, $width, $height, $mode, $playerid, $params, $urlparams) {
		global $mosConfig_live_site, $mosConfig_absolute_path;
		$config = getMgmConfig();
		if (!$playerid) $playerid=$params;
		$path = html_entity_decode($path);
		$template = "";
		if (is_dir("$mosConfig_absolute_path/templates/".$config['j_template']."/mgmediabot")) {
			$templatesdir = "$mosConfig_absolute_path/templates/".$config['j_template']."/mgmediabot";
		} else {
			$templatesdir = "$mosConfig_absolute_path/components/com_mgmedia2/templates";
		}
		$ap = Array("1","0");
		if ($templateshandle = opendir($templatesdir)) {
			while (false !== ($file = readdir($templateshandle))) {
        		if ($file != "." && $file != ".." && preg_match("#tmpl$#", $file)) {
					$contents = file_get_contents($templatesdir."/".$file);
					if (preg_match("#--start filetypes supported.*?types=.*?\b".$urlparams['type']."\b.*?--end filetypes supported(.*?)--start template(.*?)--end template#s", $contents, $matches1)) {
						if (preg_match("#--start autoplay values.*?autoplay=(.*?)--end autoplay values#s", $matches1[1], $matches2)) {
							$ap = explode(",", chop($matches2[1]));  
						}
						if (preg_match("#--start jsconfig.*?disablejavascript=(.*?)--end jsconfig#s", $matches1[1], $matches2)) {
							$GLOBALS['jscf'] = chop($matches2[1]);
						} else {
							$GLOBALS['jscf'] = false;
						}
						$template = chop($matches1[2]);
						$template = preg_replace("#\t#", "", $template);
						break;
					}
        		}
    		}
    		closedir($templateshandle);
		}
		if (isset($urlparams['autoplay'])) {
			$autoplay = $urlparams['autoplay'];
		} elseif ((($mode == "popup"|| $mode == "lightbox") && $config['popupAutorun']) || (($mode != "popup"|| $mode != "lightbox") && $config['contentAutorun'])) {
			$autoplay = $ap[0];
		} else {
			$autoplay = $ap[1];
		}
		$urlparams['autoplay'] = $autoplay;
		$urlparams['playerid'] = $playerid;
		$urlparams['mosConfig_live_site'] = $mosConfig_live_site;
        if (isset ($urlparams['path'])) {
            $urlparams['path'][0] = urldecode($urlparams['path'][0]);
        }
		if ($template == "") {
			$template = "No template of type ".$urlparams['type']." found!";
		} else {
			foreach ($urlparams as $key => $value) {
				if (is_array($value)) {
					if (count($value) > 0) {
						$template = preg_replace("#\<\{$key\}\>|<\{$key .*?\}\>#i", $value[0], $template);
					}
				} else {
					if ($value != "") {
						$template = preg_replace("#\<\{$key\}\>|<\{$key .*?\}\>#i", $value, $template);
					}
				}
			}
		}
		$template = preg_replace("#<\{.*?(default=(.*?)){0,1}\}>#s", "\\2", $template);
		return $template;
	}
	
	function createMgmPlaylist2($audiofile, $title = null, $author = null, $image = null, $link = null, $filetype = null, $description = null) {
		global $mosConfig_absolute_path, $mosConfig_live_site;
		$playlist =  '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
		$playlist .= '<playlist version="1" xmlns="http://xspf.org/ns/0/">'."\n";
		$playlist .= "\t<trackList>\n\n";
		$counter = 0;
		for ($i = 0; $i<count($audiofile); $i++) {
			$playlist .= "\t\t<track>\n";
			if (isset($title[$i])) {
				$playlist .= "\t\t\t<title>$title[$i]</title>\n";
			} else {
				$playlist .= "\t\t\t<title>$audiofile[$i]</title>\n";
			}
			if (isset($type) && $filetype == "mp3") {
				$playlist .= "\t\t\t<meta rel=\"type\">$filetype</meta>\n";
			}
			if (isset($author[$i])) {
				$playlist .= "\t\t\t<creator>".$author[$i]."</creator>\n";
			}
			if (isset($description[$i])) {
				$playlist .= "\t\t\t<annotation>".$description[$i]."</annotation>\n";
			}
			if (isset($image[$i])) {
                $playlist .= "\t\t\t<image>".$image[$i]."</image>\n";
            }
			if (isset($link[$i])) {
                $playlist .= "\t\t\t<info>".$link[$i]."</info>\n";
            }
			$audiofile[$i] = preg_replace("#\%26#", "&amp;", preg_replace("#\%3F#", "?", preg_replace("#\%3D#","=", $audiofile[$i])));
			$playlist .= "\t\t\t<location>".$audiofile[$i]."</location>\n";
			$playlist .= "\t\t</track>\n\n";	
			$counter++;
		}
		$playlist .= ("\t</trackList>\n");
		$playlist .= ("</playlist>");
		return $playlist;
	}
	
    function cleanMgmLine($line) {
        $line = preg_replace("#\t|^\s*?|^<br />|<br />$|\s*?$#m", "", $line);
        $line = preg_replace("#<br />|<p>|</p>#m", "|", $line);
        $line = preg_replace("#\|\|#m", "|", $line);
        return $line;
    }

	function parseMgmQs2($qs) {
		global $mosConfig_live_site;
		$params = preg_split('#=|,|\|#', $qs);
		if (count($params) >0 && count($params)%2 == 0) {
			for ($i=0;$i<count($params);$i+=2) {
				if ($params[$i] == "path" || $params[$i] == "title" || $params[$i] == "author" || $params[$i] == "image" || $params[$i] == "link" || $params[$i] == "filetype" || $params[$i] == "description") {
					if ($params[$i] == "path" || $params[$i] == "image") {
						if (!preg_match("#^(ftp|https|http|rtsp|mms|rtmp):\/\/|^\/#", $params[$i+1])) {
							$params[$i+1] = $mosConfig_live_site . "/" . $params[$i+1];
						}
					}
					$qss[$params[$i]][] = $params[$i+1];
				} else {
					$qss[$params[$i]] = $params[$i+1];
				}
			}
			return $qss;
		} else {
			return "Odd count of parameters!";
		}
	}
if ( !defined("CALLED_INDIRECT") ) {
	$config = getMgmConfig();
	$lastmode = mosGetParam( $_GET, 'lastmode', false );
	$mode= mosGetParam( $_GET, 'mode', false );
	$playerid = mosGetParam( $_GET, 'playerid', false );
	$query = "SELECT params FROM #__mgmediabot_playerscache WHERE md5 = '$playerid'";
    $database->setQuery( $query );
    $params = $database->loadResult($database->query());
	if ($params != "") {
		$urlparams = parseMgmQs2($params);
		if (!isset($urlparams["path"])) {$urlparams["path"] = Array(); $urlparams["path"][0] = "";}
		if (!isset($urlparams["title"])) {$urlparams["title"] = Array();}
		if (!isset($urlparams["author"])) {$urlparams["author"] = Array();}
		if (!isset($urlparams["image"])) {$urlparams["image"] = Array();}
		if (!isset($urlparams["description"])) {$urlparams["description"] = Array();}
		if (!isset($urlparams["link"])) {$urlparams["link"] = Array();}
		if (!isset($urlparams["filetype"])) {$urlparams["filetype"] = Array();}
		if (!isset($urlparams["width"])) {$urlparams["width"] = "";}
		if (!isset($urlparams["height"])) {$urlparams["height"] = "";}
		if ($mode == "script") {
			header("Content-type: text/javascript; charset=UTF-8");
			$rows = explode("\n", outputMgmPlayer2($urlparams['type'], $urlparams['path'][0],$urlparams['width'],$urlparams['height'], $lastmode, $playerid, $params, $urlparams));
			$playerjs = "";
			foreach ($rows as $key => $value) {
				$playerjs .= $value . " ";
			} 
			echo "<!--\n";
			echo "document.writeln('$playerjs');\n";
			echo "//-->";
		} elseif ($mode == "playlist"){
			$playlist =  createMgmPlaylist2($urlparams["path"], $urlparams["title"], $urlparams["author"], $urlparams["image"], $urlparams["link"], $urlparams['filetype'],$urlparams['description']);
			header("Content-type: text/xml; charset=UTF-8");
			echo $playlist;
		} elseif ($mode == "popup") {
			header("Content-type: text/html; charset=UTF-8");
			echo "<html>";
			echo "<head>";
			echo "<title>Mediaplayer</title>";
			echo "<link rel=\"Stylesheet\" type=\"text/css\" href=\"$mosConfig_live_site/components/com_mgmedia2/style.css\" />";
			echo "</head>";
			echo "<body onload=\"window.focus();\" style=\"text-align: center\" scroll=\"no\">";
			echo "<center>";
			$playercode = outputMgmPlayer2($urlparams['type'], $urlparams['path'][0],$urlparams['width'],$urlparams['height'], $mode, $playerid, $params, $urlparams);
			if (isset($GLOBALS['jscf']) && $GLOBALS['jscf']) {
				echo $playercode;
			} else {
				echo "<script language=\"Javascript\" type=\"text/javascript\" src=\"$mosConfig_live_site/index2.php?option=com_mgmedia2&mode=script&lastmode=$mode&playerid=$playerid&no_html=1\"></script>";
			}
			echo "</center>";
			echo "</body>";
			echo "</html>";
		} elseif ($mode == "lightbox") {
			header("Content-type: text/html; charset=UTF-8");
			echo "<html>";
			echo "<head>";
			echo "<title>Mediaplayer</title>";
			echo "<link rel=\"Stylesheet\" type=\"text/css\" href=\"$mosConfig_live_site/components/com_mgmedia2/style.css\" />";
			echo "</head>";
			echo "<body style=\"text-align: center\" scroll=\"no\">";
			echo "<center>";
			$playercode = outputMgmPlayer2($urlparams['type'], $urlparams['path'][0],$urlparams['width'],$urlparams['height'], $mode, $playerid, $params, $urlparams);
			if (isset($GLOBALS['jscf']) && $GLOBALS['jscf']) {
				echo $playercode;
			} else {
				echo "<script language=\"Javascript\" type=\"text/javascript\" src=\"$mosConfig_live_site/index2.php?option=com_mgmedia2&mode=script&lastmode=$mode&playerid=$playerid&no_html=1\"></script>";
			}
			echo "</center>";
			echo "</body>";
			echo "</html>";
		}
	} else {
		$warning = "Player $playerid was not found in cache!";
		if ($mode == "script") {
			echo "<!--\n";
			echo "document.writeln('$warning');\n";
			echo "//-->";
		} elseif ($mode == "popup") {
			echo $warning;
		} elseif ($mode == "playlist") {
			echo "<!-- $warning -->\n";
		}
	}
} else { ?>
		<script language="Javascript" type="text/javascript">
			function openPlayer(url, width, height) {
				var left = Math.floor((screen.width - width) / 2);
				var top = Math.floor((screen.height - height) / 2);
				window.open(url, 'mgmediabot2player', 'dependent=yes,width=' + width + ',height=' + height + ',innerwidth=' + width + ',innerheight=' + height + ',top=' + top + ',left=' + left + ',location=no,menubar=no,resizable=no,status=no,toolbar=no');
			}
		</script>
<?php
}
?>
